﻿package net.nicoptere.services 
{
	
	import flash.events.Event;
	import flash.events.ErrorEvent;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.URLRequestMethod;
	
	/**
	 * @author nicolas barradeau
	 */
	public class WebService extends EventDispatcher
	{
		
		public static const ON_RESULT:String = "webServiceResults";
		public static const ON_READY:String = "webServiceReady";
		
		public var xmlResults:XML;
		private static var _instance:WebService;
		public static function get instance():WebService
		{
			if ( _instance != null ) return _instance;
			_instance = new WebService();
			return _instance;
		}
		
		public function WebService() 
		{
			
		}
		
		//calling a method
		static public function call( serviceUrl:String, method:String, variables:URLVariables ):void
		{
			//local
			if ( Config.getProperty('local') == '1' )
			{
				instance.dispatchEvent( new Event( Event.COMPLETE ) );
				return;
			}
			/*
			var serviceUrl:String = Config.getProperty('webserviceUrl');
			var  method:String = Config.getProperty('wsMethod_user');
			var variables:URLVariables = new URLVariables();
			User.setVariables( variables );
			*/
			
			var request:URLRequest = new URLRequest( serviceUrl +'/'+ method );
			request.method = URLRequestMethod.POST;
			request.data = ( variables == null ) ? null : variables;
			
			
			var loader:URLLoader = new URLLoader();
            instance.configureListeners(loader);
            try
			{
                loader.load(request);
            }
			catch (error:Error)
			{
                trace("Unable to load requested document.");
            }
		}
		
		//configureListeners
		private function configureListeners(dispatcher:IEventDispatcher):void
		{
            
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            //dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			
        }
		private function removeListeners(dispatcher:IEventDispatcher):void
		{
            
			dispatcher.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            //dispatcher.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.removeEventListener(Event.COMPLETE, completeHandler);
			
        }
		/*
		*     Listener ERROR HANDLER
		*/
		
        private function securityErrorHandler(event:SecurityErrorEvent):void
		{
            trace("securityErrorHandler: " + event);
			removeListeners( event.target as IEventDispatcher );
			instance.dispatchEvent( new ErrorEvent( ErrorEvent.ERROR ) );
        }
        
		private function httpStatusHandler(event:HTTPStatusEvent):void
		{
            trace("httpStatusHandler: " + event);
			removeListeners( event.target as IEventDispatcher );
        }
       
		private function ioErrorHandler(event:IOErrorEvent):void
		{
            trace("ioErrorHandler: " + event);
			removeListeners( event.target as IEventDispatcher );
			instance.dispatchEvent( new ErrorEvent( ErrorEvent.ERROR ) );
        }	
		
		private function completeHandler(event:Event):void
		{
			
            var loader:URLLoader = URLLoader(event.target);
			var xResult:XML = new XML (loader.data);
			decodeWebServiceXML (xResult);
			removeListeners( event.target as IEventDispatcher );
			
        }
		private function decodeWebServiceXML (x:XML):void 
		{
			
			var ns:Namespace = new Namespace (x.namespace());
			default xml namespace = ns;
			xmlResults = x;
			
			
			if ( xmlResults.status == 0 )
			{
				instance.dispatchEvent( new Event( Event.COMPLETE ) );
			}
			else
			{
				instance.dispatchEvent( new ErrorEvent( ErrorEvent.ERROR ) );
			}
		}
	}
	
}